package org.appfuse.dao.hibernate;

import java.util.ArrayList;
import java.util.Collections;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.SessionFactory;
import org.hibernate.engine.SessionFactoryImplementor;
import org.hibernate.hql.QueryTranslator;
import org.hibernate.hql.QueryTranslatorFactory;
import org.hibernate.hql.ast.ASTQueryTranslatorFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

@Repository(value = "hqlToSqlTranslator")
public class HqlToSqlTranslator {
	protected final Log log = LogFactory.getLog(getClass());

	public String reset2NamedSql(final QueryTranslator qtranslator) {
		String fullSql = qtranslator.getSQLString();

		String[] fullSqls = StringUtils.split(fullSql, "?");

		ArrayList<String> pNameList = new ArrayList();
		for (Object obj : qtranslator.getParameterTranslations()
				.getNamedParameterNames()) {
			String name = (String) obj;
			log.debug("name=" + name);
			int[] indexs = qtranslator.getParameterTranslations()
					.getNamedParameterSqlLocations(name);
			log.debug("indexs.length=" + indexs.length);
			int j = 0;
			for (int index : indexs) {
				log.debug("index" + (j++) + "=" + index);
				pNameList.add(index, name);
			}
		}

		StringBuffer fullSqlsb = new StringBuffer();
		int count = 0;
		for (String sqlSect : fullSqls) {
			fullSqlsb.append(sqlSect);
			if (count < pNameList.size()){
				fullSqlsb.append(":" + pNameList.get(count));
				count++;
			}
		}

		return fullSqlsb.toString();
	}

	private SessionFactory sessionFactory;

	@Autowired
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	public QueryTranslator toSql(String hqlQueryText) {
		if (hqlQueryText != null && hqlQueryText.trim().length() > 0) {
			final QueryTranslatorFactory translatorFactory = new ASTQueryTranslatorFactory();
			final SessionFactoryImplementor factory = (SessionFactoryImplementor) sessionFactory;
			final QueryTranslator translator = translatorFactory
					.createQueryTranslator(hqlQueryText, hqlQueryText,
							Collections.EMPTY_MAP, factory);
			translator.compile(Collections.EMPTY_MAP, false);
			return translator;
		}
		return null;
	}
}